package cn.com.dhcc.turbo.web.controller.account;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.HookPara;
import cn.com.dhcc.app.core.annotation.SiNoNeedLogin;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
import cn.com.dhcc.turbo.service.sysmgr.UserMgrService;

/**
 * 包含非中央节点用户登录，注销，注册等功能，
 * 
 * @see {@link cn.gov.mwr.si.core.web.interceptor.AuthInterceptor} 权限验证
 * @日期：2012-12-27下午4:54:28
 * @作者：乔兵
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("account/")
public class LoginController extends BaseController {

	@Autowired
	private UserMgrService userMgrService;
	public static String LOCAL_NODE_SESSION_KEY = "_local_node_session";
	public static String NET_TYPE_KEY = "_netType";
	public static String HAS_GAP_KEY = "_hasGap";
	public static final String LOG_PAGE = "account/login";
	public static final String INDEX_ACTION = "/monitor/ontime.do";
	
	
	@Autowired
	NodeInfoService nodeInfoService;

	// private static Logger logger = Log.getDetachLogger(LOGTYPE.R);

	/**
	 * 登录验证 针对没有单点登录的节点
	 * 
	 * @param model
	 * @param httpSession
	 * @param userCode
	 * @param password
	 * @return
	 */
	@RequestMapping("login")
	@SiNoNeedLogin
	public String login(Model model, HttpSession httpSession, String userName, String password) {
		if (getUserSessionVo(httpSession) != null) {
			return "redirect:/account/index.do";
		}
		if (StringUtils.hasText(userName) && StringUtils.hasText(password)) {
			UserInfo userInfo = null;
			try {
				userInfo = userMgrService.getUserInfoByUserName(userName);
				if (userInfo != null) {
					if (!userInfo.getPwd().equalsIgnoreCase(password)) {
						model.addAttribute("error", "用户密码错误！");
						return LOG_PAGE;
					}
				} else {
					model.addAttribute("error", "用户[" + userName + "]不存在！");
					return LOG_PAGE;
				}
				userInfo.setSlAuthFlag(userMgrService.getUserAuthFlag(userInfo));
				httpSession.setAttribute(HAS_GAP_KEY, NodeInfoParam.hasGap);
				httpSession.setAttribute(HookPara.USER_SESSION_KEY, userInfo);
				try {
					//验证节点是否已经初始化
					httpSession.setAttribute(NET_TYPE_KEY, NodeInfoParam.NODE_NET_TYPE);
					NodeInfo nodeInfo = nodeInfoService.getLocalNode();
					if(nodeInfo!=null){
						httpSession.setAttribute(LOCAL_NODE_SESSION_KEY, nodeInfo);
					}
				} catch (Exception e) {
					model.addAttribute("error", "系统异常,请联系管理员！");
					return LOG_PAGE;
				}
				return "redirect:/account/index.do";
			} catch (Exception e1) {
				model.addAttribute("error", "系统异常,请联系管理员！");
				return LOG_PAGE;
			}
		} else {
			return LOG_PAGE;
		}
	}

	@RequestMapping("index")
	@SiNoNeedLogin
	public String index(Model model, HttpSession httpSession) {
		return "redirect:" + INDEX_ACTION;
	}

	@SiNoNeedLogin
	@RequestMapping("logout")
	public String logout(HttpSession httpSession) {
		httpSession.invalidate();
		return "redirect:/account/login.do";
	}

	/**
	 * 密码修改页面
	 * @param model
	 * @param httpSession
	 * @return
	 */
	@RequestMapping(value = "/password_change")
	public String passwordChange(Model model, HttpSession httpSession) {
		UserInfo user = (UserInfo) getCurrentUserInfo(httpSession);
		model.addAttribute("user", user);
		return "account/password_change";
	}

	/**
	 * 执行密码修改操作
	 * @param model
	 * @param httpSession
	 * @param oldPassword
	 * @param newPassword
	 * @return
	 */
	@RequestMapping(value = "/password_do_change")
	@ResponseBody
	public Map<String, Object> changePassword(Model model, HttpSession httpSession, String oldPassword,
			String newPassword) {
		try {
			if (StringUtils.hasText(oldPassword)) {
				UserInfo user = (UserInfo) getCurrentUserInfo(httpSession);
				if (user != null) {
					if (!user.getPwd().equals(oldPassword)) {
						return jsonFailResult("用户密码错误");
					} else {
						userMgrService.changePwdByUserId(user.getId(), newPassword);
						return jsonSuccessResult("用户密码成功");
					}
				} else {
					return jsonFailResult("用户名不存在");
				}
			} else {
				return jsonFailResult("用户名或密码为空");
			}
		} catch (Exception e1) {
			model.addAttribute("error", "系统异常,请联系管理员！");
			return jsonFailResult("系统异常,请联系管理员！");
		}
	}
}
